import axios from 'axios'
import config from '@/config'
import {getToken} from "../util";
import qs from 'Qs'

import {Message,Loading} from 'element-ui'

export const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro


const service = axios.create({
  baseURL: baseUrl, // api的base_url
  timeout: 5000          // 请求超时时间
});

export default service

let loading;

// request拦截器，实现loading加载
service.interceptors.request.use(config => {
  const token = getToken()
  console.log(token)
  config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
  if (token) {
    config.headers['Token'] = token;
  }
  config.timeout = 60000;

  // if (config.url.indexOf("login") == -1) {
  //   if (!token||token==''){
  //     router.push({name:"login"})
  //     return Promise.reject("请先登录")
  //   }
  // }
  if (config.method === 'get') {
    // 如果是get请求，且params是数组类型如arr=[1,2]，则转换成arr=1&arr=2
    config.paramsSerializer = function(params) {
      return qs.stringify(params, { arrayFormat: 'repeat' })
    }
  } else {
    if (loading) {
      loading.close()
    }
    loading = Loading.service({
    		  lock: false,
    		  text: '拼命加载中...',
    		  background:'rgba(255,255,255,0.5)',
    })
  }
  return config
}, error => {
  return Promise.reject(error)
})

// response拦截器，实现loading关闭
service.interceptors.response.use(resp => {
  if (loading) {
    loading.close()
  }
  if(resp.headers['content-type'] == 'application/octet-stream'){
    return resp;
  }
  const {code,msg,data} = resp.data
  if (code != 200) {
    Message({type: 'error',message: msg});
    return Promise.reject(msg)
  }
  return data
}, error => {
  if (loading) {
    loading.close()
  }
  return Promise.reject(error)
})
